<template>
  <div class="Echarts">
    <div :id="uuid" :style="style">
      Echarts
    </div>
  </div>
</template>

<script>
import * as echarts from "echarts";

const idGen = () => {
  return new Date().getTime();
};

export default {
  props: {
    height: {
      type: String,
      default: "400px",
    },

    width: {
      type: String,
      default: "600px",
    },

    options: {
      type: Object,
      default: null,
    },
  },

  data() {
    return {
      uuid: null,
      myChart: null,
      startValue: 0,
      endValue: 5,
      timerId: null,
    };
  },
  destroyed() {
    clearInterval(this.timerId);
  },
  computed: {
    style() {
      return {
        height: this.height,
        width: this.width,
      };
    },
  },

  created() {
    this.uuid = idGen();
  },

  mounted() {
    this.myChart = echarts.init(document.getElementById(this.uuid));

    this.myChart.setOption(this.options);

    this.myChart.on('mouseover', ()=>{
      clearInterval(this.timerId);
    });
    this.myChart.on('mouseout',() => {
      this.startInterval();
    })

    this.startInterval();
  },

  watch: {
    options() {
      this.myChart.setOption(this.options);
      if (this.timerId) {
        clearInterval(this.timerId);
        this.startValue = 0;
        this.endValue = 5;
      }
      this.startInterval();
    },
    startValue() {
      this.options.dataZoom.startValue = this.startValue;
      this.myChart.setOption(this.options);
    },
    endValue() {
      this.options.dataZoom.endValue = this.endValue;
      this.myChart.setOption(this.options);
    },
  },

  methods: {
    startInterval() {
      if (this.timerId) {
        clearInterval(this.timerId);
      }
      this.timerId = setInterval(() => {
        this.startValue++;
        this.endValue++;
        if (this.endValue >= this.options.xAxis.data.length) {
          this.startValue = 0;
          this.endValue = 5;
        }
      }, 2000);
    },
  },
};
</script>

<style></style>
